<template>
  <view class="user-login-container">
    <uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>
    <button type="warn" class="btn" open-type="getUserInfo" @getuserinfo="getUserInfo">一键登录</button>
    <!-- <button type="warn" class="btn" @click="getUserInfo">一键登录</button> -->
    <text class="tips">登录后尽享更多权益</text>
  </view>
</template>

<script>
  import {
    mapMutations,
    mapGetters
  } from 'vuex'
  export default {
    name: "user-login",
    data() {
      return {

      };
    },
    computed:{
      ...mapGetters(['redirectInfo'])
    },
    methods: {
      ...mapMutations('userInfo', ['updateUserInfo','updateRedirect']),
      // 一键登录
      async getUserInfo(e) {
        // console.log(e);
        /* const [err,res] = await uni.getUserProfile({
          desc:'用来获取小程序的授权'
        }) */
        const data = await uni.getUserInfo()
        console.log(data);
        // 将获取到的用户资料存到vuex中
        this.updateUserInfo(e.detail.userInfo)
        // 获取用户登录凭证
        this.getLogin(e.detail)
      },
      async getLogin(detail) {
        const [err, res] = await uni.login()
        // console.log(uni.getAccountInfoSync())
        // 获取到用户登录凭证
        // console.log(detail);
        if (err && res.errMsg !== 'login:ok') return uni.showToast({title:'登陆失败'})
        let loginBodyData = {
          code: res.code,
          signature: detail.signature,
          rawData: detail.rawData,
          iv: detail.iv,
          encryptedData: detail.encryptedData
        }
        // console.log(loginBodyData);
        // 发送登录请求
        const data = await uni.$http.post('/users/wxlogin',JSON.stringify(loginBodyData))
        console.log(data);
        // 模拟登录成功，然后跳转到之前的页面
        if(data.statusCode === 200){
          if(this.redirectInfo ?. openType === 'switchTab' ) {
            uni.switchTab({
              url:this.redirectInfo.from,
              complete: () => {
                this.updateRedirect(null)
              }
            })
          }
        }
      }
    }
  }
</script>

<style lang="scss">
  .user-login-container {
    height: 90%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .btn {
      width: 80%;
      line-height: 40px;
      border-radius: 20px;
      color: #fff;
      background-color: #C00000;
      margin: 18px 0;
    }

    .tips {
      font-size: 14px;
      color: #afafaf;
    }
  }
</style>
